package com.helper.debugger.utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import java.util.List;

public class SimCardHelper {
    public static String[] getAllSimCardCountryCodes(Context context) {
        String[] countryCodes = new String[1];
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            // 多卡处理
            SubscriptionManager sm = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
            if (sm != null) {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    countryCodes[0] = getSimCardCountryCode(context);
                } else {
                    List<SubscriptionInfo> subscriptions = sm.getActiveSubscriptionInfoList();
                    if (subscriptions != null) {
                        countryCodes = new String[subscriptions.size()];
                        for (int i = 0; i < subscriptions.size(); i++) {
                            int subId = subscriptions.get(i).getSubscriptionId();
                            TelephonyManager tm = context.getSystemService(TelephonyManager.class).createForSubscriptionId(subId);
                            countryCodes[i] = tm.getSimCountryIso();
                        }
                    }
                }
            }
        } else {
            // 单卡处理
            countryCodes[0] = getSimCardCountryCode(context);
        }
        return countryCodes;
    }

    public static String getSimCardCountryCode(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm != null ? tm.getSimCountryIso() : null;
    }

    private static void log(String msg) {
        Log.i("[B]" + SimCardHelper.class.getSimpleName(), msg);
    }

    private static void error(String msg) {
        Log.e("[B]" + SimCardHelper.class.getSimpleName(), msg);
    }
}
